package io.github.biezhi.wechat.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 日期工具类
 *
 * @author biezhi
 * @date 2018/1/19
 */
@Slf4j
public class DateUtils {

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");

    public static void sendSleep(){
        int rand = 2 + WeChatUtils.random(100, 3000);
        DateUtils.sleep(rand);
    }

    /** 存放不同的日期模板格式的sdf的Map */
    private static ThreadLocal<Map<String, SimpleDateFormat>> sdfMap = ThreadLocal.withInitial(HashMap::new);

    /**
     * 休眠，单位: 毫秒
     *
     * @param ms
     */
    public static void sleep(long ms) {
        try {
            TimeUnit.MILLISECONDS.sleep(ms);
        } catch (InterruptedException e) {
            log.error("", e);
        }
    }

    public static String dateToStr(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        String str = null;
        try {
            SimpleDateFormat format = getSdf(pattern);
            str = format.format(date);
            format = null;
        } catch (Exception e) {
        }
        return str;
    }

    private static SimpleDateFormat getSdf(final String pattern) {
        return getSdf(pattern, Locale.CHINESE);
    }

    private static SimpleDateFormat getSdf(final String pattern, Locale locale) {
        Map<String, SimpleDateFormat> tl = sdfMap.get();
        SimpleDateFormat sdf = tl.get(pattern);
        if (sdf == null) {
            sdf = new SimpleDateFormat(pattern, locale);
            tl.put(pattern, sdf);
        }
        return sdf;
    }

    /**
     * 获取字符串日期
     *
     * @return
     */
    public static String getDateString() {
        return DATE_FORMAT.format(new Date());
    }

}
